package com.learn.xueer.app.network

import com.learn.xueer.app.util.CacheUtil
import com.learn.xueer.ui.activity.LoginActivity
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.util.ActivityMessenger
import me.hgj.jetpackmvvm.util.LogUtils
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * 自定义头部参数拦截器，传入heads
 */
class MyHeadInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val builder = chain.request().newBuilder()

        if (CacheUtil.getToken().isNotEmpty())
            builder.header("token", CacheUtil.getToken())
        var proceed = chain.proceed(builder.build())

        if (proceed.code() == 401) {
            LogUtils.debugInfo("1111111")

            CacheUtil.clearAll()
            ActivityMessenger.startActivityNew(appContext, LoginActivity::class)
            KtxActivityManger.finishAllActivity()
        }

        return proceed
    }

}